package cn.changein.framework.config.filter;

import cn.changein.framework.util.ThreadContextHolder;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**

 */
@Slf4j
public class ThreadContextHolderFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String userId = request.getHeader("userid");
            if (userId != null) {
                ThreadContextHolder.setUserId(Long.parseLong(userId));
            }
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            ThreadContextHolder.remove();
        }

    }
}
